<template>
  <div class="hot-boke-page">
    <div style="text-align: left;">
      <router-link to="/home"><el-i class="fas fa-home" style="color: black;"></el-i></router-link> 
    </div>
   
    <h1 style="color: black;">热门博客</h1>
    <div v-if="posts.length > 0" class="grid-container">
      <div
        v-for="post in posts"
        :key="post.PostID"
        class="box"
        @click="goToBokeInfo(post)"
      >
        <div class="content">
          <h2 class="post-title">{{ post.PostTitle }}</h2>
          <p class="post-content">
            {{ post.PostContent.length > 40 ? post.PostContent.slice(0, 40) + '......' : post.PostContent }}
          </p>
          <p class="post-meta">
            <span><strong>发布者ID:</strong> {{ post.Post_UserID }}</span>
            <span><strong>发布时间:</strong> {{ formatDate(post.Post_Date) }}</span>
          </p>
        </div>
      </div>
    </div>
    <p v-else>暂无热门博客。</p>
  </div>
</template>


<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import instance from '../api/server';
 
// 博客数据
const posts = ref([]); 
const router = useRouter(); 

// 获取博客数据
const fetchPosts = async () => {
  try {
    const response = await instance.get('/myinfo/blog/getpopularpost');
    posts.value = response.data.data; // 确保正确访问数据
    console.log(response.data.data);
  } catch (error) {
    console.error('API 请求错误:', error);
    if (error.response && error.response.status === 401) {
      console.error('未经授权，请检查令牌是否有效');
    }
  }
};

// 跳转到博客详情页面
const goToBokeInfo = (post) => {
  const postID = post.PostID;
  router.push(`/bokeinfo/${postID}`);
};

// 格式化日期
const formatDate = (dateStr) => {
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 页面加载时获取博客数据
onMounted(() => {
  fetchPosts();
});
</script>


<style src="../assets/style/HotBoke.css" scoped></style>
